<template>
  <view class="order-comment">
    <view class="header">
      <view class="title">订单评价</view>
      <view class="sub-title">您的评价将帮助我们改进服务</view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-list">
      <view class="goods-item" v-for="(item, itemIndex) in orderItems" :key="item.id"
        :style="{ animationDelay: itemIndex * 0.1 + 's' }">
        <view class="goods-info">
          <image class="goods-image" :src="item.productImage" mode="aspectFill" />
          <view class="goods-detail">
            <view class="goods-name">{{ item.productName }}</view>
            <view class="goods-params" v-if="item.params">{{ item.params }}</view>
            <view class="goods-price" v-if="item.price">¥{{ item.price }}</view>
          </view>
        </view>

        <!-- 商品评分 -->
        <view class="rating-section">
          <view class="section-header">
            <view class="rating-title">商品评分</view>
            <view class="rating-value">{{ item.rating }}分</view>
          </view>
          <view class="custom-rate">
            <view v-for="i in 5" :key="i" class="rate-item" @click="setItemRating(itemIndex, i)">
              <view class="rate-star" :class="{ 'active': item.rating >= i }"></view>
            </view>
          </view>
        </view>

        <!-- 快捷评价标签 -->
        <view class="tags-section">
          <view v-for="(tag, tagIndex) in quickTags" :key="tagIndex" class="tag-item"
            :class="{ active: item.selectedTags.includes(tag) }" @click="toggleTag(itemIndex, tag)">
            {{ tag }}
          </view>
        </view>

        <!-- 商品评价 -->
        <view class="comment-section">
          <wd-textarea v-model="item.comment" maxlength="200" show-word-limit placeholder="请对该商品进行评价，如：商品质量，满意度等"
            custom-style="border-radius: 12rpx; background: #f9f9f9; padding: 24rpx; box-sizing: border-box; font-size: 28rpx;" />
        </view>
      </view>
    </view>

    <!-- 订单整体评价 -->
    <view class="order-rating">
      <view class="order-rating-title">订单整体评价</view>

      <view class="rating-row">
        <view class="rating-label">
          <text>订单评分</text>
          <text class="rating-desc">{{ getRatingDesc(orderRating.overall) }}</text>
        </view>
        <view class="rating-value-wrapper">
          <text class="rating-value">{{ orderRating.overall }}分</text>
          <view class="custom-rate">
            <view v-for="i in 5" :key="i" class="rate-item" @click="setOrderRating(i)">
              <view class="rate-star" :class="{ 'active': orderRating.overall >= i }"></view>
            </view>
          </view>
        </view>
      </view>

      <view class="order-comment-section">
        <wd-textarea v-model="orderComment" maxlength="200" show-word-limit placeholder="请对本次购物体验进行评价"
          custom-style="border-radius: 12rpx; background: #f9f9f9; padding: 24rpx; box-sizing: border-box; font-size: 28rpx;" />
      </view>

      <!-- 匿名评价 -->
      <view class="anonymous-section">
        <view class="anonymous-content">
          <view class="anonymous-title">匿名评价</view>
          <view class="anonymous-desc">开启后，您对本订单及商品的所有评价将以匿名形式展示</view>
        </view>
        <wd-switch v-model="isAnonymous" size="20px" active-color="#3e89fa" />
      </view>
    </view>

    <!-- 提示信息 -->
    <view class="tips-section">
      <view class="tips-icon">
        <wd-icon name="wd-icon-info" size="26px" color="#999"></wd-icon>
      </view>
      <view class="tips-content">
        <view class="tips-title">评价提交后</view>
        <view class="tips-desc">· 评价一经提交将无法修改</view>
        <view class="tips-desc">· 您的评价将帮助其他用户做出更好的选择</view>
        <view class="tips-desc">· 真实客观的评价更有参考价值</view>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-section">
      <view class="submit-inner">
        <wd-button type="primary" block @click="submitComment"
          custom-style="border-radius: 12rpx; height: 88rpx; font-size: 32rpx; font-weight: 500;">提交评价</wd-button>
      </view>
    </view>

    <!-- 提交确认弹窗 -->
    <wd-message-box />
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useMessage } from '@/uni_modules/wot-design-uni'
import { onLoad } from '@dcloudio/uni-app'
import { getOrderDetail, submitReviews } from '@/api/order'

// 获取路由参数
const orderId = ref('')
const orderNo = ref('')

// 统一匿名设置
const isAnonymous = ref(false)

// 快捷评价标签
const quickTags = [
  '物美价廉',
  '质量很好',
  '服务周到',
  '外观精美',
  '性价比高',
  '物流快速',
  '包装完好',
  '使用方便'
]

// 商品评价数据
const orderItems = ref([])
// 订单整体评价
const orderRating = ref({
  overall: 5
})
const orderComment = ref('')

// 提交确认弹窗
const message = useMessage()

// 设置商品评分
const setItemRating = (itemIndex, rating) => {
  if (itemIndex >= 0 && itemIndex < orderItems.value.length) {
    // 使用Vue的响应式API确保更新被正确跟踪
    const newItems = [...orderItems.value];
    newItems[itemIndex] = { ...newItems[itemIndex], rating };
    orderItems.value = newItems;
  }
}

// 设置订单评分
const setOrderRating = (rating) => {
  // 使用Vue的响应式API确保更新被正确跟踪
  orderRating.value = { ...orderRating.value, overall: rating };
}

// 获取评分描述
const getRatingDesc = (rating) => {
  if (rating >= 5) return '非常满意'
  if (rating >= 4) return '满意'
  if (rating >= 3) return '一般'
  if (rating >= 2) return '不满意'
  return '非常不满意'
}

// 切换标签选择状态
const toggleTag = (itemIndex, tag) => {
  if (itemIndex < 0 || itemIndex >= orderItems.value.length) return;

  const item = orderItems.value[itemIndex];
  if (!item.selectedTags) {
    item.selectedTags = [];
  }

  const tagIndex = item.selectedTags.indexOf(tag);

  // 创建新的数组来确保触发Vue的响应式
  const newItems = [...orderItems.value];
  const newItem = { ...newItems[itemIndex] };
  const newSelectedTags = [...newItem.selectedTags || []];

  if (tagIndex > -1) {
    newSelectedTags.splice(tagIndex, 1);
  } else {
    newSelectedTags.push(tag);

    // 如果评价内容为空，自动添加标签内容到评价中
    if (!newItem.comment) {
      newItem.comment = newSelectedTags.join('，');
    } else if (!newItem.comment.includes(tag)) {
      // 如果评价内容中不包含该标签，则添加
      newItem.comment = newItem.comment + '，' + tag;
    }
  }

  newItem.selectedTags = newSelectedTags;
  newItems[itemIndex] = newItem;
  orderItems.value = newItems;
}

// 获取订单详情
const getOrderInfo = async (id) => {
  uni.showLoading({ title: '加载中' })
  try {
    const data = await getOrderDetail(id)
    const order = data
    orderNo.value = order.orderNo

    // 初始化商品评价数据
    orderItems.value = order.items.map(item => ({
      ...item,
      rating: 5,
      comment: '',
      selectedTags: []
    }))
    console.log(orderItems.value)
  } catch (error) {
    uni.showToast({
      title: error.message || '获取订单详情失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 提交评价
const submitComment = () => {
  // 验证评价内容
  for (const item of orderItems.value) {
    if (!item.comment.trim()) {
      return uni.showToast({
        title: '请填写所有商品的评价内容',
        icon: 'none'
      })
    }
  }

  if (!orderComment.value.trim()) {
    return uni.showToast({
      title: '请填写订单整体评价',
      icon: 'none'
    })
  }

  message
    .confirm({
      msg: '评价提交后不可修改，是否确认提交？',
      title: '提交评价'
    })
    .then(() => {
      confirmSubmit()
    })
    .catch(() => {
      console.log('点击了取消按钮')
    })
}

// 确认提交评价
const confirmSubmit = async () => {
  uni.showLoading({ title: '提交中' })
  try {
    // 构建提交的数据
    const productEvaluateList = orderItems.value.map(item => ({
      productId: item.productId,
      productName: item.productName,
      rating: item.rating,
      reviewText: item.comment
    }))

    // 准备提交的数据
    const evaluateData = {
      orderId: Number(orderId.value),
      orderNo: orderNo.value,
      rating: orderRating.value.overall,
      reviewText: orderComment.value,
      anonymous: isAnonymous.value ? 1 : 0,
      productEvaluateList: productEvaluateList
    }

    // 调用API提交评价
    await submitReviews(evaluateData)

    uni.hideLoading()
    uni.showToast({
      title: '评价提交成功',
      icon: 'success',
      duration: 2000,
      success: () => {
        // 返回订单详情页
        setTimeout(() => {
            uni.navigateTo({
              url: '/pages/order/list?type=0'
            })
          }, 2000)
      }
    })
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: error.message || '评价提交失败',
      icon: 'none'
    })
  }
}

// 页面加载
onLoad((options) => {
  if (options.orderId) {
    orderId.value = options.orderId
    getOrderInfo(orderId.value)
  } else {
    uni.showToast({
      title: '订单参数错误',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }
})
</script>

<style lang="scss">
.order-comment {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 160rpx;

  .header {
    background: linear-gradient(135deg, #4e94fa, #5d9dfe);
    padding: 40rpx 30rpx;
    color: #fff;
    box-shadow: 0 4rpx 16rpx rgba(62, 137, 250, 0.2);

    .title {
      font-size: 40rpx;
      font-weight: bold;
      margin-bottom: 12rpx;
    }

    .sub-title {
      font-size: 26rpx;
      opacity: 0.8;
    }
  }

  .goods-list {
    padding: 20rpx;

    .goods-item {
      background-color: #fff;
      margin-bottom: 24rpx;
      padding: 30rpx;
      border-radius: 16rpx;
      box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
      animation: fadeInUp 0.5s ease forwards;
      opacity: 0;
      transform: translateY(20rpx);

      .goods-info {
        display: flex;
        margin-bottom: 30rpx;
        position: relative;

        .goods-image {
          width: 160rpx;
          height: 160rpx;
          border-radius: 12rpx;
          flex-shrink: 0;
          box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
          transition: transform 0.3s;

          &:active {
            transform: scale(1.05);
          }
        }

        .goods-detail {
          flex: 1;
          margin-left: 24rpx;
          padding-top: 10rpx;
          display: flex;
          flex-direction: column;

          .goods-name {
            font-size: 30rpx;
            font-weight: 500;
            color: #333;
            margin-bottom: 16rpx;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
          }

          .goods-params {
            font-size: 24rpx;
            color: #999;
            margin-bottom: 16rpx;
            padding: 4rpx 12rpx;
            background-color: #f5f5f5;
            border-radius: 8rpx;
            display: inline-block;
            max-width: 90%;
          }

          .goods-price {
            font-size: 28rpx;
            color: #ff5722;
            font-weight: 500;
            margin-top: auto;
          }
        }
      }

      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        .rating-title {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }

        .rating-value {
          font-size: 28rpx;
          color: #ff9900;
          font-weight: 500;
        }
      }

      .rating-section {
        margin-bottom: 30rpx;
      }

      .tags-section {
        display: flex;
        flex-wrap: wrap;
        margin: 0 -8rpx 24rpx;

        .tag-item {
          margin: 8rpx;
          padding: 12rpx 20rpx;
          background-color: #f5f5f5;
          border-radius: 30rpx;
          font-size: 24rpx;
          color: #666;
          transition: all 0.2s;

          &.active {
            background-color: #ebf3ff;
            color: #3e89fa;
            font-weight: 500;
          }

          &:active {
            transform: scale(0.95);
          }
        }
      }

      .comment-section {
        margin-bottom: 0;
      }
    }
  }

  .order-rating {
    background-color: #fff;
    padding: 30rpx;
    margin: 0 20rpx 30rpx;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
    animation: fadeIn 0.5s ease 0.3s forwards;
    opacity: 0;

    .order-rating-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 30rpx;
      position: relative;
      padding-left: 20rpx;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 6rpx;
        height: 30rpx;
        background: #3e89fa;
        border-radius: 3rpx;
      }
    }

    .rating-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      padding: 10rpx 0;

      .rating-label {
        font-size: 28rpx;
        color: #333;
        display: flex;
        flex-direction: column;

        .rating-desc {
          font-size: 22rpx;
          color: #999;
          margin-top: 6rpx;
        }
      }

      .rating-value-wrapper {
        display: flex;
        flex-direction: column;
        align-items: flex-end;

        .rating-value {
          font-size: 28rpx;
          color: #ff9900;
          font-weight: 500;
          margin-bottom: 6rpx;
        }
      }
    }

    .order-comment-section {
      margin-top: 30rpx;
      margin-bottom: 30rpx;
    }

    .anonymous-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24rpx 0 8rpx;
      border-top: 1px solid #f0f0f0;

      .anonymous-content {
        .anonymous-title {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 8rpx;
        }

        .anonymous-desc {
          font-size: 22rpx;
          color: #999;
          max-width: 540rpx;
        }
      }
    }
  }

  .tips-section {
    background-color: #fff;
    padding: 24rpx 30rpx;
    margin: 0 20rpx 30rpx;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
    display: flex;
    animation: fadeIn 0.5s ease 0.4s forwards;
    opacity: 0;

    .tips-icon {
      margin-right: 16rpx;
      flex-shrink: 0;
      margin-top: 2rpx;
    }

    .tips-content {
      flex: 1;

      .tips-title {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        margin-bottom: 10rpx;
      }

      .tips-desc {
        font-size: 24rpx;
        color: #999;
        line-height: 1.6;
      }
    }
  }

  .submit-section {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(255, 255, 255, 0.98);
    box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.08);
    z-index: 10;

    .submit-inner {
      max-width: 750rpx;
      margin: 0rpx auto;
      padding: 16rpx 30rpx calc(10rpx + env(safe-area-inset-bottom, 0));
    }
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

.custom-rate {
  display: flex;
  touch-action: none;
  /* 防止移动端上的手势冲突 */

  .rate-item {
    position: relative;
    padding: 0 4rpx;
    cursor: pointer;
    min-width: 50rpx;
    height: 50rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .rate-star {
      width: 38rpx;
      height: 38rpx;
      position: relative;
      display: inline-block;
      background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%23D8D8D8' d='M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z'/%3E%3C/svg%3E") no-repeat center/contain;

      &.active {
        background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%23ff9900' d='M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z'/%3E%3C/svg%3E") no-repeat center/contain;
      }
    }

    &:active {
      transform: scale(1.1);
    }
  }
}
</style>